import { IAppOption, IProductDetail } from "../../../typings"
import { ICartItem, IModalCarts, IModalOrders } from "../../../typings/types/cloud-models"
import { getProductDetail } from "../../api/getProductDetail"
import { EOrderStatus, EPaymentMethod, EPaymentStatus, ESelectionType } from "../../models/enum"
import { eventBus } from "../../utils/util"

const app = getApp<IAppOption>()
Component({
  properties: {
    visible: {
      type: Boolean,
      value: false
    },
    product: {
      type: Object,
      value: {}
    }
  },
  data: {
    visible: false,
    product: {} as IProductDetail,
    quantity: 1,
    loading: false,
    selectedPrice: 0,
    selectedSpecsText: '',
    isValid: false,
    hasCartBar: false,
  },
  observers: {
    'visible': function (visible) {
      if (visible && this.properties.product && this.properties.product._id) {
        this.setData({
          quantity: 1
        })
        this.fetchSpecs()
      }
    },
    'product': function (product) {
      if (product && product._id) {
        this.setData({
          selectedPrice: product.price || 0
        })
      }
    }
  },
  lifetimes: {
    created() {
      this.setData({
        hasCartBar: app.globalData.cart.length > 0
      })
      eventBus.on("cartUpdated", () => {
        this.setData({
          hasCartBar: app.globalData.cart.length > 0
        })
      })
    }
  },
  methods: {
    // 处理抽屉显示状态变化
    onVisibleChange(e: WechatMiniprogram.CustomEvent) {
      const visible = e.detail.visible
      this.setData({ visible })

      if (!visible) {
        // 关闭抽屉时重置数据
        this.setData({
          selectedSpecs: [],
          quantity: 1,
          selectedSpecsText: '',
          isValid: false
        })
        this.triggerEvent('close')
      }
    },
    onStepperChange(e: any) {
      this.setData({
        quantity: e.detail.value
      })
    },
    // 获取商品规格信息
    async fetchSpecs() {
      const productId = this.properties.product._id
      if (!productId) return

      this.setData({ loading: true })

      try {
        const detail = await getProductDetail(productId, false)
        if (detail !== undefined && detail !== null) {
          this.setData({
            product: detail
          })
          this.validateSelection()
        }
      }
      catch {
        wx.showToast({
          title: '获取规格信息失败',
          icon: 'none'
        })
      }
      this.setData({ loading: false })
    },
    // 处理规格选择
    onSpecSelect(e: WechatMiniprogram.TouchEvent) {
      const { groupId, specId, selectionType } = e.currentTarget.dataset

      const { product } = this.data
      const groupIndex = product.specs.findIndex(item => item._id === groupId)

      if (groupIndex === -1) return

      const newProduct = product

      const itemIndex = newProduct.specs[groupIndex].items.findIndex(i => i._id === specId);
      // 单选模式
      if (selectionType === ESelectionType.single) {
        // 如果已选中，则取消选中
        newProduct.specs[groupIndex].items = newProduct.specs[groupIndex].items.map(i => ({
          ...i,
          isSelected: false
        }))
        newProduct.specs[groupIndex].items[itemIndex].isSelected = !newProduct.specs[groupIndex].items[itemIndex].isSelected
      }
      // 多选模式
      else {
        if (itemIndex === -1) {
          // 添加选中
          newProduct.specs[groupIndex].items[itemIndex].isSelected = false
        } else {
          // 取消选中
          newProduct.specs[groupIndex].items[itemIndex].isSelected = !newProduct.specs[groupIndex].items[itemIndex].isSelected
        }
      }

      this.setData({
        product: newProduct
      })
      this.updateSelectedPrice()
      this.updateSelectedSpecsText()
      this.validateSelection()

    },
    // 更新选中规格的价格
    updateSelectedPrice() {
      const { product } = this.data
      let totalAdditionalPrice = product.specs.reduce((accumulator, currentValue) => accumulator + currentValue.items.filter(i => i.isSelected).reduce((acc, item) => acc + item.price, 0), 0)

      // 基础价格 + 附加价格
      const selectedPrice = (product.price || 0) + totalAdditionalPrice

      this.setData({ selectedPrice })
    },
    // 更新已选规格文本
    updateSelectedSpecsText() {
      const { product } = this.data
      const selectedTexts: string[] = product.specs.filter(i => i.items.some(j => j.isSelected)).map(i => `${i.name}: ${i.items.map(j => j.name).join(', ')}`)

      this.setData({
        selectedSpecsText: selectedTexts.join('; ')
      })
    },
    // 验证规格选择是否有效
    validateSelection(): boolean {
      const { product } = this.data
      let isValid = true

      // 检查必选规格组是否已选择
      product.specs.forEach(group => {
        if (group.required) {
          const selectedGroup = group.items.some(item => item.isSelected === true)
          if (!selectedGroup) {
            isValid = false
          }
        }
      })

      this.setData({ isValid })
      return isValid
    },
    // 添加到购物车
    addToCart() {
      if (!this.validateSelection()) {
        wx.showToast({
          title: '请选择必选规格',
          icon: 'none'
        })
        return
      }

      const { product, quantity, selectedPrice, selectedSpecsText } = this.data

      // 创建购物车商品对象
      const cartItem = {
        ...product,
        selectedSpecsText,
        quantity,
        price: selectedPrice
      } as (IProductDetail & {
        selectedSpecsText: string
        quantity: number
        price: number
      })


      const carts = app.globalData.cart || []

      // 查找购物车中是否已有相同商品（相同ID和规格）
      const index = carts.findIndex((item: ICartItem) => {
        if (cartItem.isBundle && item.bundleItems !== undefined) {
          const bundleItemsSpecKey = item.bundleItems.map(i => i.specKey).join('-');
          const bundleCartItemsSpecKey = cartItem.bundleItems.map(i => i.items.map(j => j.specKey).join('-')).join('-');
          return item.bundleId === cartItem._id && bundleItemsSpecKey === bundleCartItemsSpecKey
        }
        else
          return item.productId === cartItem._id && item.specKey === cartItem.specKey
      })

      if (index > -1) {
        // 如果已存在，增加数量
        carts[index].quantity! += cartItem.quantity || 1
      } else {
        // 如果不存在，添加新项
        carts.push({
          ...cartItem,
          quantity: cartItem.quantity || 1,
          isSelected: true,
          productId: product._id,
          bundleId: '',
          bundleItems: []
        })
      }

      app.globalData.cart = carts
      wx.setStorageSync('carts', carts)

      // 触发购物车更新事件
      eventBus.emit('cartUpdated', carts)

      wx.showToast({
        title: '已加入购物车',
        icon: 'success'
      })

      // 关闭抽屉
      this.setData({ visible: false })

      // 触发事件通知父组件
      this.triggerEvent('cartchange', { product: cartItem })
    },
    // 立即购买
    buyNow() {
      if (!this.validateSelection()) {
        wx.showToast({
          title: '请选择必选规格',
          icon: 'none'
        })
        return
      }

      const { product, quantity, selectedPrice, selectedSpecsText } = this.data

      // 创建订单商品对象
      const orderItem = {
        orderNo: app.generateOrderNo(),
        totalAmount: selectedPrice,
        totalPayable: selectedPrice,
        paymentMethod: EPaymentMethod.wechat,
        // memberDiscount: , 
        paymentStatus: EPaymentStatus.unpaid,
        status: EOrderStatus.pending,
        items: [
          {
            image: product.image,
            // bundleItems: product.isBundle?product.bundleItems.flatMap(i=>i.items.map(j=>({
            //   image: j.image,
            //   groupName: i.groupName,
            //   quantity: j.quantity,
            //   productId: j,
            //   price: j,
            //   groupId: j,
            //   name: j,
            //   specKey: j,
            //   selectedSpecs
            // }))):undefined,
            quantity: quantity,
            productId: product.isBundle ? 0 : product._id,
            price: selectedPrice,
            bundleId: product.isBundle ? product._id : 0,
            name: product.name,
            specKey: product.specKey,
            selectedSpecs: product.specs.map(i => ({
              groupId: i._id,
              specIds: i.items.map(j => j._id)
            }))
          }
        ]
      } as IModalOrders

      // 将商品信息存储到本地，用于订单确认页面获取
      wx.setStorageSync('buyNowItem', orderItem)

      // 关闭抽屉
      this.setData({ visible: false })

      // 跳转到订单确认页面
      wx.navigateTo({
        url: '/pages/order/confirm/confirm?from=buynow'
      })
    },
  }
})